package com.syeet.gulimall.product.web;

import com.syeet.gulimall.product.entity.CategoryEntity;
import com.syeet.gulimall.product.service.CategoryService;
import com.syeet.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author xhl
 * @date 2022/5/27
 */
@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping(value = {"/", "/index.html"})
    public String indexPage(Model model) {

        //查询所有一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Category();
        model.addAttribute("categorys", categoryEntities);
        return "index";
    }

    /**
     * index/catalog.json
     */
    @GetMapping("index/catalog.json")
    @ResponseBody
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        Map<String, List<Catelog2Vo>> map = categoryService.getCatelogJson();
        return map;
    }

    /**
     * 模拟业务,基于Redis的Redisson分布式可重入锁RLock
     *
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/hello")
    public String hello() {
        //1 获取锁，只要锁的名字一样，就是同一把锁
        RLock clientLock = redissonClient.getLock("my-lock");
        //加锁
        clientLock.lock(); //阻塞式等待，默认锁的过期时间为30s

        // 1锁的自动续期，如果业务执行时间过长，看门狗自动给续上新的30s,无需担心业务时间长，导致锁的过期被删掉
        //2 加锁的业务完成，就不会给当前锁续期，即使不手动解锁，也会在30s后释放锁
//        clientLock.lock(10, TimeUnit.SECONDS);//10s过期，自动解锁时间一定要大于业务执行时间

        //问题
        // 该clientLock.lock(10, TimeUnit.SECONDS)方法在锁到时间后不会像clientLock.lock()自动续期
        //1.如果我们设置了超时时间，就会给redis发送lua脚本，默认超时时间就是我们设定的时间
        //2.如果我们未设置了超时时间，就使用30*1000【lockWatchdogTimeout看门狗默认时间，即30s】,只要占锁成功
        //就会启动一个定时任务（new TimerTask）,重新给锁设置过期时间，新的过期时间为30s
        //this.internalLockLeaseTime(看门狗默认时间) / 3L,就是每隔10s续期,自动续到30s

        //最佳实战
        //clientLock.lock(30, TimeUnit.SECONDS) 我们自己给定锁的过期时间，
        // 就是要注意自动解锁时间一定要大于业务执行时间，手动解锁，这种做法省掉续期操作
        try {
            System.out.println("加锁成功 ...执行业务，锁id:" + Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (Exception e) {

        } finally {
            //解锁
            System.out.println("释放锁，锁id:" + Thread.currentThread().getId());
            clientLock.unlock();
        }
        return "hello";
    }

    /**
     * 模拟业务,基于Redis的Redisson分布式可重入读写锁RReadWriteLock
     * 保证一定能读到最新的值，写锁是个排他锁（互斥锁），读锁是个共享锁
     * 写锁没释放就必须等待
     * 读+读：相当于无锁，并发读，同时成功
     * 先写+后读：等待写锁释放
     * 写+写： 阻塞模式
     * 读+写：有读锁，写需要等待
     * 只要有写的存在，都会等待
     *
     * @return
     */
    @ResponseBody
    @GetMapping(value = "write")
    public String writeValue() {
        //改数据加写锁，读数据加读锁
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
        RLock writeLock = readWriteLock.writeLock();
        String s = "";
        try {
            writeLock.lock();
            s = UUID.randomUUID().toString();
            System.out.println("写锁加锁成功：" + Thread.currentThread().getId());
            Thread.sleep(30000);
            stringRedisTemplate.opsForValue().set("writeValue", s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
            System.out.println("写锁释放锁成功：" + Thread.currentThread().getId());
        }
        return s;
    }

    /**
     * 模拟业务,基于Redis的Redisson分布式可重入读写锁RReadWriteLock
     *
     * @return
     */
    @ResponseBody
    @GetMapping(value = "read")
    public String readValue() {
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
        RLock readLock = readWriteLock.readLock();
        readLock.lock();
        String s = "";
        try {
            System.out.println("读锁加锁成功：" + Thread.currentThread().getId());
            s = stringRedisTemplate.opsForValue().get("writeValue");
            Thread.sleep(30000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
            System.out.println("读锁释放锁成功：" + Thread.currentThread().getId());
        }
        return s;
    }

    /**
     * 车库停车
     * 3车位
     * 信号量也可以做分布式限流
     */
    @GetMapping(value = "/park")
    @ResponseBody
    public String park() throws InterruptedException {

        RSemaphore park = redissonClient.getSemaphore("park");
        // park.acquire();     //获取一个信号、获取一个值,占一个车位
        boolean flag = park.tryAcquire();

        if (flag) {
            //执行业务
        } else {
            return "error";
        }
        return "ok=>" + flag;
    }

    @GetMapping(value = "/go")
    @ResponseBody
    public String go() {
        RSemaphore park = redissonClient.getSemaphore("park");
        park.release();     //释放一个车位
        return "ok";
    }


    /**
     * 放假、锁门
     * 1班没人了
     * 5个班，全部走完，我们才可以锁大门
     * 分布式闭锁
     */

    @GetMapping(value = "/lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {

        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.trySetCount(5);
        door.await();       //等待闭锁完成
        return "放假了...";
    }

    @GetMapping(value = "/gogogo/{id}")
    @ResponseBody
    public String gogogo(@PathVariable("id") Long id) {
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.countDown();       //计数-1
        return id + "班的人都走了...";
    }

}
